package gson;

import static com.google.gson.stream.JsonToken.END_DOCUMENT;

import com.google.gson.stream.*;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.List;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class JsonReaderTest {

  static Resource jsonResource = new ClassPathResource("example.json");


  static JsonPath sourcePath = JsonPath.compile("$.hits.hits[*]._source");

  public static void main(String[] args) throws Exception {

    DocumentContext documentContext = JsonPath.parse(jsonResource.getInputStream());

    List<Object> sources = documentContext.read(sourcePath);

    //JsonReader reader = new JsonReader(new InputStreamReader(jsonResource.getInputStream()));

    if (sources != null) {

      for (Object source : sources) {
        System.out.println(source);
        JsonReader reader = new JsonReader(new StringReader(JsonPath.parse(source).jsonString()));
        reader.setLenient(true);
        JsonToken token;
        while ((token = reader.peek()) != END_DOCUMENT) {
          switch (token) {
            case BEGIN_ARRAY:
              reader.beginArray();
              break;
            case END_ARRAY:
              reader.endArray();
              break;
            case BEGIN_OBJECT:
              reader.beginObject();
              break;
            case END_OBJECT:
              reader.endObject();
              break;
            case NAME:
              String name = reader.nextName();
              System.out.println("name==>" + name);
              break;

            case STRING:
            case NUMBER:
              String value = reader.nextString();
              String path = reader.getPath();
              System.out.println("value:" + value + ",path:" + path);
              //String path = reader.getPath().replaceAll("\\[\\d+\\]", "[*]");

              break;

            case BOOLEAN:
              reader.nextBoolean();
              break;

            case NULL:
              reader.nextNull();
              break;
            case END_DOCUMENT:
              break;
          }
        }
      }
    }
  }
}